package other.xsy.pms;

import com.rkhd.platform.sdk.data.model.QuoteLine;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.pms.utils.HCXObjectService;

import java.util.ArrayList;
import java.util.List;

public class QuoteDetailTrigger implements Trigger {

    private static final Logger logger = LoggerFactory.getLogger();
    private static HCXObjectService hcxObjectService = new HCXObjectService();


    @Override
    public TriggerResponse execute(TriggerRequest request) {
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        ArrayList<QuoteLine> quoteLineList = new ArrayList<>();
        for (XObject xObject : dataList) {
            QuoteLine quoteLine = (QuoteLine) xObject;
            Long id = quoteLine.getId();
            QuoteLine handler = handler(id);
            quoteLineList.add(handler);
            dataResultList.add(new DataResult(true, "", handler));
        }
        return new TriggerResponse(true, "", dataResultList);
    }

    private QuoteLine handler(Long id) {
        logger.info("报价单明细id为" + id);
        QuoteLine quoteLine = new QuoteLine();
        quoteLine.setId(id);
        try {
            QuoteLine quoteLine1 = hcxObjectService.get(quoteLine);
            //数量
            Double quantity = quoteLine1.getQuantity();
            //周期
            Double cycle__c = quoteLine1.getCycle__c();
            //折扣后净价
            Double price = quoteLine1.getPrice();
            //计算合同总价
            Double allAmount = quantity * cycle__c * price;
            quoteLine1.setAmount(allAmount);
            Boolean update = hcxObjectService.update(quoteLine1);
            if (!update) {
                throw new Exception("更新失败，报价单明细id为" + id);
            }
            return quoteLine1;
        } catch (Exception e) {
            logger.error("系统错误！！！" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}
